<template>
<div class="blog-toc-container" >
  <h2>目录</h2>
  <RightList :list="setwhitisSelect" @select="hanleSelect"></RightList>
</div>
  
</template>

<script>
import { debounce } from '../../../utils';
import RightList from './RightList.vue';
export default {
  data(){
    return{
      activeanchor:'',
    }
  },
    components: { RightList },
    props:{
      toc:{
        type:Array,
      }
    },
computed:{
   getDoms(){ 
      const doms= [];
      const addToDoms = (toc)=>{
         for (const dom of toc) {
           doms.push(document.querySelector(`#${dom.anchor}`))
           if(dom.children && dom.children.length){
               addToDoms(dom.children)
           }
         }
      }
 addToDoms(this.toc)
//  console.log(doms)
 return doms;
},
setwhitisSelect(){
 const getToc=(toc=[])=>{
  return toc.map(t=>({
    ...t,
    isSelect:t.anchor === this.activeanchor,
    children:getToc(t.children),
  }))
   }
   return  getToc(this.toc)
    }
},
 created(){
   // console.log(this.getDom) 函数防抖

this.desetactivelist=this.debounce(this.setactivelist,50)
   this.$Bus.$on('mainScroll',this.desetactivelist)
 },
 destroyed(){
   this.$Bus.$off('mainScroll',this.desetactivelist)
 },
    methods:{
      debounce,
 hanleSelect(item){
     location.hash=item.anchor;
      },
      //activeAnchor 正确的值
 setactivelist( dom){
   if(!dom){
     return
   }
   this.activeanchor='';//由于后续要设置先清空之前状态
   const spacing=200;
   
for (const item of this.getDoms) {
  if(!item){//判断有没有这个原素，
    continue;
  }
  let dis=item.getBoundingClientRect();
  if(dis.top>0&&dis.top<=spacing){
    this.activeanchor=item.id//范围内
    return
  }else if(dis.top>spacing){//范围下都没有激活
    return
  }else{
    this.activeanchor=item.id//范围上
  }
}
 }

       }
}
</script>

<style lang="less" scoped>

   h2{
   font-weight: bold;
   font-size: 1em;
   letter-spacing: 2px;
   margin:0;
   }

</style>